using System;
using System.Collections.Generic;
using System.Linq;
using dbvc.Queries;

namespace App_Code.Context
{
    public class Column
    {
        public string Name { get; set; }
        public string Sort { get; set; }
        public int Width { get; set; }
    }

    public interface IQuery
    {
        string Sort { get; set; }
        bool IsAsc { get; set; }
        void SortBy(string field);

        int PageIndex { get; set; }
        int PageSize { get; set; }
        int PageCount { get; set; }
        
        void Goto(int i);
    }

    public class Query<T> : IQuery
    {
        // metadata for controls
        public int PageIndex { get; set; }
        public int PageSize { get; set; }
        public int PageCount { get; set; }

        public string Sort { get; set; }
        public bool IsAsc { get; set; }

        public List<T> Records { get; set; }
        public IQueryable<T> Source { get; set; }

        public IEnumerable<T> Execute()
        {
            PageCount = Source.Count()/ PageSize+1;

            if (PageIndex > PageCount) PageIndex = 1;

            Records = Source
                .OrderBy(Sort, IsAsc)
                .Skip((PageIndex - 1)*PageSize)
                .Take(PageSize).ToList();

            return Records;
        }

        public void First(){ Goto(1); }
        public void Next() { Goto(PageIndex++); }
        public void Prior(){ Goto(PageIndex--); }
        public void Last() { Goto(PageCount); }
        
        public void Goto(int pageindex)
        {
            PageIndex = pageindex;
            Execute();
        }

        public void SortBy(string field)
        {
            PageIndex = 1;
            if (Sort == field) IsAsc = !IsAsc;
            else
            {
                Sort = field;
                IsAsc = true;
            }

            Execute();
        }
    }
}